package com.friend.common.interceptor;

import com.friend.common.event.QuestionChangeEvent;
import com.friend.mapper.question.QuestionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 题目变更拦截器
 * 自动检测数据库变更并发布事件
 */
@Component
@Slf4j
public class QuestionChangeInterceptor {
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    @Autowired
    private QuestionMapper questionMapper;
    
    /**
     * 发布题目变更事件
     */
    public void publishQuestionChangeEvent(Long questionId, QuestionChangeEvent.Operation operation) {
        try {
            QuestionChangeEvent event = new QuestionChangeEvent(this, questionId, operation);
            eventPublisher.publishEvent(event);
            log.info("发布题目变更事件 - questionId: {}, operation: {}", questionId, operation);
        } catch (Exception e) {
            log.error("发布题目变更事件失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 批量发布题目变更事件
     */
    public void publishBatchQuestionChangeEvent(List<Long> questionIds, QuestionChangeEvent.Operation operation) {
        try {
            for (Long questionId : questionIds) {
                publishQuestionChangeEvent(questionId, operation);
            }
            log.info("批量发布题目变更事件 - 数量: {}, operation: {}", questionIds.size(), operation);
        } catch (Exception e) {
            log.error("批量发布题目变更事件失败: {}", e.getMessage(), e);
        }
    }
}
